package com.pet.server.ext.action.request;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.BeanToJson;
import com.pet.server.ext.Result;
import com.pet.server.ext.data.AnswerInfo;
import com.pet.server.ext.data.RequestInfo;
import com.pet.server.ext.service.RequestService;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.NumberUtil;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.StringUtil;
public class Session extends ActionBase{

	public Integer requestId,userId;
	
	public Session(){
		 needCheckAuth =true;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {
		requestId = NumberUtil.getInteger(params.getFieldValue("request_id"));
		userId=NumberUtil.getInteger(params.getFieldValue("user_id"));
		if(StringUtil.isEmpty(requestId,userId)){
			throw ApiError.Type.INVALID_PARAM.toException();
		}
	}
	@Override
	public Result invokeService() throws ApiError {
		JSONObject data = new JSONObject();
		UserService userService = new UserService();
		RequestService requestService = new RequestService();
		RequestInfo request = userService.findRequestInfo(requestId);
		if(null==request){
			throw ApiError.Type.LOGIC_ERROR.toException("信息不存在!");
		}
		String sessionid = StringUtil.createSessionid(userId, requestId);
		java.util.List<AnswerInfo> list = requestService.queryAnswerInfobySessionId(sessionid);
		JSONArray array = BeanToJson.listTojson(list,"reply_id");
		for(int i=0;i<array.size();i++){
			JSONObject o = array.getJSONObject(i);
			o.accumulate("questioner", request.getUser_id()==o.getInt("user_id")?"1":"0");
		}
	    data.put("detail", BeanToJson.beanToJson(request, "answer_id"));
	    data.put("list", array);
		Result result = new Result();
        result.put("data", data);		
		return result;
	}
}
